#!/usr/bin/python

import urllib,urllib2,re,xbmcplugin,xbmcgui
import os,datetime,base64
from BeautifulSoup import BeautifulStoneSoup
pluginhandle = int(sys.argv[1])

################################ Common
txheaders = {
    'Referer': 'http://www.history.com',
    'X-Forwarded-For': '12.13.14.15',
    'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US;rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 ( .NET CLR 3.5.30729)',
}
fanart_links = {'american-pickers':'http://thetvdb.com/banners/fanart/original/141181-2.jpg',
                'pawn-stars':'http://thetvdb.com/banners/fanart/original/111051-1.jpg',
                'american-restoration':'http://thetvdb.com/banners/fanart/original/199011-1.jpg',
		'ancient-aliens':'http://thetvdb.com/banners/fanart/original/101501-3.jpg',
		'ice-road-truckers':'http://thetvdb.com/banners/fanart/original/80273-2.jpg',
		'swamp-people':'http://thetvdb.com/banners/fanart/original/183231-3.jpg',
		'top-gear':'http://thetvdb.com/banners/fanart/original/199051-1.jpg',
		'the-universe':'http://thetvdb.com/banners/fanart/original/80198-1.jpg',
		'cajun-pawn-stars':'http://thetvdb.com/banners/fanart/original/254650-1.jpg'
               }
icon_links = {'american-pickers':'http://thetvdb.com/banners/_cache/posters/141181-2.jpg',
              'pawn-stars':'http://thetvdb.com/banners/_cache/posters/111051-3.jpg',
              'american-restoration':'http://thetvdb.com/banners/_cache/posters/199011-1.jpg',
              'ancient-aliens':'http://thetvdb.com/banners/_cache/posters/101501-1.jpg',
              'ice-road-truckers':'http://thetvdb.com/banners/_cache/posters/80273-2.jpg',
              'swamp-people':'http://thetvdb.com/banners/_cache/posters/183231-3.jpg',
              'top-gear':'http://thetvdb.com/banners/_cache/posters/199051-2.jpg',
              'the-universe':'http://thetvdb.com/banners/_cache/posters/80198-3.jpg',
	      'cajun-pawn-stars':'http://thetvdb.com/banners/_cache/posters/254650-1.jpg'
	      }



def getURL( url ):
    try:
        print 'History Channel --> getURL :: url = '+url
	txdata = None
        global txheaders  
        req = urllib2.Request(url, txdata, txheaders)
        response = urllib2.urlopen(req)
	link=response.read()
	response.close()
    except urllib2.URLError, e:
        error = 'Error code: '+ str(e.code)
        xbmcgui.Dialog().ok(error,error)
        print 'Error code: ', e.code
        return False
    else:
        return link


def addLink(name,url,mode,smil,iconimage='',plot='',season=0,episode=0,showname='',duration='',fanart='special://home/addons/plugin.video.history.channel/fanart.jpg'):
   name = name.encode('raw-unicode-escape')
   u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+'&smil='+urllib.quote_plus(smil)
   ok=True
   liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
   liz.setInfo( type="Video", infoLabels={ "Title": name,
                                           "Plot":plot,
                                           "Season":season,
                                           "Episode":episode,
                                           "Duration":duration,
                                           "TVShowTitle":showname})
   if fanart!='':
      liz.setProperty('fanart_image', fanart)
   liz.setProperty('IsPlayable', 'true')
   ok=xbmcplugin.addDirectoryItem(handle=pluginhandle,url=u,listitem=liz)
   return ok

def addDir(name,url,mode,iconimage='',plot='',fanart='special://home/addons/plugin.video.history.channel/fanart.jpg'):
   u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+'&thumbnail='+urllib.quote_plus(iconimage)
   ok=True
   liz=xbmcgui.ListItem(name, iconImage='DefaultFolder.png', thumbnailImage=iconimage)
   liz.setInfo( type="Video", infoLabels={ "Title": name, "Plot":plot})
   if fanart!='':
      liz.setProperty('fanart_image', fanart);
   ok=xbmcplugin.addDirectoryItem(handle=pluginhandle,url=u,listitem=liz,isFolder=True)
   return ok

################################ Root listing
def ROOT():
   xbmcplugin.addSortMethod(pluginhandle, xbmcplugin.SORT_METHOD_LABEL)
   data = getURL("http://www.history.com/shows")
   show_pages = re.compile('class="watch more" href="/shows/(.+)/videos"').findall(data)

   global fanart_links
   global icon_links 

   for show in show_pages:
      if hasFullEpisodes(show):
         mode=3 #EPISODE Mode
	 pretty_name = show.replace('-', ' ')
	 pretty_name = pretty_name.title()
         fanart = 'special://home/addons/plugin.video.history.channel/fanart.jpg'
	 icon = 'special://home/addons/plugin.video.history.channel/icon.png'
         if show in fanart_links:
	    fanart = fanart_links[show]
	 if show in icon_links:
	    icon = icon_links[show]
	 addDir(pretty_name,show,mode,icon,'',fanart)
   
   xbmcplugin.endOfDirectory(pluginhandle)

def EPISODE(name, sid):
   showname = name
   xbmcplugin.setContent(pluginhandle, 'episodes')
   xbmcplugin.addSortMethod(pluginhandle, xbmcplugin.SORT_METHOD_NONE)

   global fanart_links 
   global icon_links 

   episode_list = getEpisodeList(sid)
   for episode in episode_list:
      name = episode[0]
      thumbnail = episode[1]
      duration = episode[2]
      plot = episode[3]
      smil = episode[4]
      seasonNum = 0;
      episodeNum = 0;
      mode = 5 #PLAYEPISODE
      fanart = 'special://home/addons/plugin.video.history.channel/fanart.jpg'
      if sid in fanart_links:
         fanart = fanart_links[sid]
      addLink(name,sid,mode,smil,thumbnail,plot,seasonNum,episodeNum,showname,duration,fanart)
   xbmcplugin.endOfDirectory(pluginhandle)

def PLAYEPISODE(name, sid, smil):
   #data = getURL(smil)
   #base = re.compile('{"videoURLs":{"releaseURL":"(.+?)"').findall(data)[0]

   base = smil;
   smil_url = re.compile('.+?/s/(.+)').findall(smil)[0]

   #sig = getURL('http://servicesaetn-a.akamaihd.net/jservice/video/components/get-signed-signature?url='+smil_url)
   sig = getURL('http://www.history.com/components/get-signed-signature?url='+smil_url)
   
   url = base+'?sig='+sig+'&format=SMIL&Tracking=true&Embedded=true'
   data = getURL(url)

   media_url = re.compile('video src="(.+?)"').findall(data)[0]

   item = xbmcgui.ListItem(path=media_url)
   return xbmcplugin.setResolvedUrl(pluginhandle, True, item)

def hasFullEpisodes(show):
   if show in fanart_links:
      return True
   else: 
      return False

def getEpisodeList(show):
   episode_list = []
   url = 'http://www.history.com/shows/'+show+'/videos/playlists/full-episodes'
   data = getURL(url);

   infos = re.compile('{"videoURLs":{"releaseURL":"(.+?)","html5ReleaseURL":"(.+?)"},"siteUrl":"(.+?)","display":{"title":"(.+?)","description":"(.+?)","duration":"(.+?)","videoPageUrl":"(.+?)","slug":"(.+?)","thumbUrl":"(.+?)","rating":"(.+?)"}.+?"premium":"(.+?)"').findall(data)

   for info in infos:
   	if( info[10] == "false"):
	   	episode_list.append((info[3], info[8], info[5], info[4], info[0]))

   return episode_list   


def get_params():
   param=[]
   paramstring=sys.argv[2]
   print paramstring
   if len(paramstring)>=2:
      params=sys.argv[2]
      cleanedparams=params.replace('?','')
      if (params[len(params)-1]=='/'):
         params=params[0:len(params)-2]
      pairsofparams=cleanedparams.split('&')
      param={}
      for i in range(len(pairsofparams)):
         splitparams={}
         splitparams=pairsofparams[i].split('=')
         if (len(splitparams))==2:
            param[splitparams[0]]=splitparams[1]
                                
   return param


params=get_params()
url=None
name=None
mode=None
smil=None

try:
        url=urllib.unquote_plus(params["url"])
except:
        pass
try:
        name=urllib.unquote_plus(params["name"])
except:
        pass
try:
        mode=int(params["mode"])
except:
        pass
try:
        smil=urllib.unquote_plus(params["smil"])
except:
        pass

print "Mode: "+str(mode)
print "URL: "+str(url)
print "Name: "+str(name)
print "Smil:"+str(smil)

if mode==None or url==None or len(url)<1:
   ROOT()
elif mode==1:
   pass
elif mode==2:
   pass
elif mode==3:
   EPISODE(name,url)
elif mode==4:
   pass
elif mode==5:
   PLAYEPISODE(name, url, smil)

	       
